import { getPermissionListApi, getRoleDetailApi, updateRoleApi } from "@/api/modules/user";
import { Button, Card, Transfer } from "antd";
import type { TransferDirection } from "antd/es/transfer";
import React, { useEffect, useState } from "react";
import styles from "./index.module.less";
import { useLocation } from "react-router-dom";
import { User } from "@/api/interface";
import useMessage from "@/hooks/useMessage";

interface RecordType {
	key: string;
	title: string;
	description: string;
}

const RolePermission: React.FC = () => {
	const [targetKeys, setTargetKeys] = useState<string[]>([]);
	const [originData, setOriginData] = useState<RecordType[]>([]);
	const getPermissionList = async (page: number = 1, size: number = 999) => {
		const res = await getPermissionListApi(page, size);
		if (res.code === 200) {
			const oriData: RecordType[] = res.data.rows.map(item => {
				return {
					key: item.id.toString(),
					title: item.name,
					description: `description of content${item.action}`
				};
			});
			setOriginData(oriData);
		}
	};

	useEffect(() => {
		getPermissionList();
		if (state?.id) {
			getRoleDetail(state.id);
		}
	}, []);

	const handleChange = (newTargetKeys: string[]) => {
		setTargetKeys(newTargetKeys);
	};

	const getRoleDetail = async (id: number) => {
		const res = await getRoleDetailApi(id);
		if (res.code === 200) {
			setRole(res.data);
			setTargetKeys((res.data.permissions as User.Permission[]).map(item => String(item.id)));
		}
	};
	const { contextHolder, success, error } = useMessage();
	const location = useLocation();
	const state: any = location.state;

	const [role, setRole] = useState<User.Role>({
		id: -1,
		name: "无",
		permissions: [],
		createdAt: "",
		updatedAt: ""
	});

	const onSave = async () => {
		if (role.id == -1) return error("请到我的角色面板确定角色");
		const permissions = targetKeys.map(item => Number(item));
		const res = await updateRoleApi({
			id: role.id,
			name: role.name,
			permissions: permissions
		});
		if (res.code === 200) success("保存成功");
		else error("保存失败");
	};

	return (
		<div className={styles.root}>
			{contextHolder}
			<Card>
				<div className="topInfo">
					<div>当前角色: {role.name}</div>
					<Button onClick={onSave}>保存</Button>
				</div>
			</Card>
			<Card className="transfer">
				<Transfer
					dataSource={originData}
					showSearch
					listStyle={{
						width: 600,
						height: 500
					}}
					titles={["全部", "已分配"]}
					oneWay
					targetKeys={targetKeys}
					onChange={handleChange}
					render={item => item.title}
				/>
			</Card>
		</div>
	);
};

export default RolePermission;
